//
//  MTInAppPurchases ViewController.swift
//  MT
//
//  Created by ooops on 2020/3/17.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import YPNavigationBarTransition
import SwiftyStoreKit
import MBProgressHUD
import RxCocoa
import Moya
import Result
import MTCategory

extension MTInAppPurchasesViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // TODO:- Required Method
        return self.result.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: MTPaymentItemCell = collectionView.dequeueReusableCell(withReuseIdentifier: MTPaymentItemCell.reuseIdentity(), for: indexPath) as! MTPaymentItemCell
        configureCell(cell: cell, forItemAt: indexPath)
        // TODO:- Required Method
        return cell
    }
    
    func configureCell(cell: MTPaymentItemCell, forItemAt indexPath: IndexPath) {
        let model = self.result[indexPath.item]
        cell.model = model
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.result[indexPath.item]
        //model.isSelected = true
        removeLayer(indexPath: indexPath)
        if let productId = model.code {
            inApp(productId: productId)
        }
    }
    
    private func removeLayer(indexPath: IndexPath) {
        
        for i in 0..<self.result.count {
            let model = self.result[i]
            if indexPath.item == i {
                model.isSelected = true
            } else {
                model.isSelected = false
            }
        }
        
        self.collectionView.reloadData()
        
    }
}


class MTInAppPurchasesViewController: BaseViewController {
    
    var paymentViews: [MTPaymentItemView] = []
    private lazy var payProvider: MTProvider<MTPaymentAPI> = {
        let provider = MTProvider<MTPaymentAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    /// collection view
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        let inset: CGFloat = 15.0
        let itemWidth = (ScreenWidth - inset * 4 - 1) / 3
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth * 88 / 105)
        flowLayout.minimumLineSpacing = 15
        flowLayout.minimumInteritemSpacing = 15
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MiTuGiftView.collectionViewHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.common.x161616
        cv.contentInset = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
//        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTPaymentItemCell.self, forCellWithReuseIdentifier: MTPaymentItemCell.reuseIdentity())
        return cv
    }()
    
    private var result: [MTApplePaymentResultModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "钻石充值"
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        //setupUI()
        loadData()
    }
    
    override func refreshView() {
        self.collectionView.reloadData()
    }
    
    private func loadData() {
        
        payProvider.rx.requestResult(.appleList).subscribe(onNext: { (result:Result<MTPaymentModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let model):
                if model.code == 200, let r = model.appleResult {
                    DispatchQueue.main.async {
                        self.result = r
                        //self.setupUI()
                        self.collectionView.reloadData()
                    }
                }
            case .failure(_):
                break
            }
            
        }).disposed(by: globalDisposedBag)
        
    }
    
    /// 内购支付
    private func inApp(productId: String) {
        MBProgressHUD_JChat.showLoading(self.view, text: "正在请求苹果服务器")
        SwiftyStoreKit.purchaseProduct(productId, atomically: true) { result in
            MBProgressHUD_JChat.showLoading(self.view, text: "商品购买完成, 正在验证")
            switch result {
            case .success(let purchase):
                // Deliver content from server, then:
                if purchase.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                }
                
                
                /// 验证票据合法
                let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "c95ec806272a465eb28e60fc465fa891")
                SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: false) { result in
                    switch result {
                    case .success(_):
                        //debugPrint("Verify receipt success:", self.jsonToData(jsonDic: receipt)?.base64EncodedString())
                        /// 获取支付的订单base64
                        if let receiptData = SwiftyStoreKit.localReceiptData {
                            let receiptString = receiptData.base64EncodedString(options: [])
                            /// 本地存一份支付票据的信息
                            UserDefaults.Enviroment.localReceiptBase64Data.store(value: receiptString)
                            self.payload(payload: receiptString)
                        } else {
                            MBProgressHUD_JChat.dismiss(self.view)
                            MBProgressHUD_JChat.showLoading(self.view, text: "订单数据异常, 请稍后重试")
                        }
                    case .error(let error):
                        MBProgressHUD_JChat.dismiss(self.view)
                        MBProgressHUD_JChat.showLoading(self.view, text: "订单验证失败, 请稍后重试")
                        debugPrint("Verify receipt failed: \(error)")
                    }
                }
            case .error(let error):
                debugPrint(error)
                MBProgressHUD_JChat.dismiss(self.view)
                MBProgressHUD_JChat.show(text: error.localizedDescription, view: self.view)
            }
        }
    }
    
    func jsonToData(jsonDic:Dictionary<String, Any>) -> Data? {
        if (!JSONSerialization.isValidJSONObject(jsonDic)) {
            debugPrint("is not a valid json object")

            return nil
    }
        let data = try? JSONSerialization.data(withJSONObject: jsonDic, options: [])
        //Data转换成String打印输出
        let str = String(data:data!, encoding: String.Encoding.utf8)
        //输出json字符串
        debugPrint("Json Str:\(str!)")
        return data
    }
    
    /// 验证内购订单数据
    private func payload(payload: String) {
        
        payProvider.rx.requestResult(.iosPay(payload: payload)).subscribe(onNext: { (result:Result<MTPaymentModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let model):
                MBProgressHUD_JChat.dismiss(self.view)
                if model.code == 200 {
                    MBProgressHUD_JChat.show(text: "商品验证完成", view: self.view, 2)
                    /// 清除本地缓存的内购票据信息
                    UserDefaults.Enviroment.localReceiptBase64Data.store(value: nil)
                } else {
                    MBProgressHUD_JChat.show(text: "订单数据验证异常, 请联系客服", view: self.view, 2)
                }
            case .failure(_):
                MBProgressHUD_JChat.dismiss(self.view)
                MBProgressHUD_JChat.show(text: "订单数据验证异常, 请联系客服", view: self.view, 2)
                break
            }
            
        }).disposed(by: globalDisposedBag)
        
    }

}

extension MTInAppPurchasesViewController {

    override func yp_navigationBarTintColor() -> UIColor! {
        return UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack]
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        return UIColor(hex: 0xFFFFFF)
    }
}
